﻿using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using Telerik.Web.UI;
using MediaMonitor.Common;
using System.Web.Security;

namespace MediaMonitor.Users
{
    public partial class Report_All_Filter : Adex.BasePage
    {

        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        private int mediaTypeCode = 0;
        private string mediaCodes_TV = "";
        private string mediaCodes_Radio = "";
        private string mediaCodes_Cable = "";
        private string mediaCodes_Press = "";
        private string mediaCodes_Outdoor = "";
        private string mediaCodes_Internet = "";

        private string mediaCodes_Competition = "";

        private int programCode = 0;
        private string sectorCode = "", subSectorCode = "", subSector2Code = "", categoryCode = "";
        string advertiserCode = "", brandCode = "", productCode = "", versionCode = "", agencyCode = "";
        int sTime = 0, eTime = 0;
        int sLength = 0, eLength = 0;
        int posInBreak = 0;
        int sPrice = 0, ePrice = 0;
        bool firstAppearanceOnly = false;
        bool DownloadOnly = false;
        bool DownloadOnlyProduct = false;
        bool DownloadOnlyAdvertiser = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PremissionForModules();
                Utility.AddDateControlToPage(this.Page);
                SetCalendarDates();
               

                FillMediaTypes();

                FillSectors();
                FillSubSectors();
                FillCategories();
                FillAdvertisers();
                FillAgencies();

                Session["UserWriteProductName"] = "";
                Session["SearchMediaCodes_Competition"] = "";
                GetLatestRecords();
               

            }
        }


        private void GetLatestRecords()
        {
            DataTable dt = RfController.GetLastAvailable_All();
            if (dt.Rows.Count > 0)
            { 
            lblTVMax.Text=dt.Rows[0][0].ToString();
                lblRadioMax.Text=dt.Rows[0][0].ToString();;
                lblCableMax.Text=dt.Rows[0][0].ToString();;
                lblPressMax.Text = dt.Rows[1][0].ToString();
                    lblOutdoorMax.Text=dt.Rows[3][0].ToString();
                    lblInternetMax.Text = dt.Rows[2][0].ToString(); 

            }
        
        }


        private void PremissionForModules()
        {
            
            String UserID = String.Empty;
            String ReturnValue=String.Empty;

            MembershipUser memUsr = System.Web.Security.Membership.GetUser();
            if (memUsr != null)
            {
                UserID = memUsr.ProviderUserKey.ToString();
            }
            ReturnValue = RfController.GetSiteUsers_ModuleStatusAll(UserID);

            if (ReturnValue.Contains(1.ToString())) //TV
            {
                trMedia_TV.Visible = true;
                chkAll_TV.Checked = true;
            }

            if (ReturnValue.Contains(3.ToString())) //Radio
            {
                trMedia_Radio.Visible = true;
                chkAll_Radio.Checked = true;
            }

            if (ReturnValue.Contains(5.ToString())) //Cable
            {
                trMedia_Cable.Visible = true;
                chkAll_Cable.Checked = true;
            }

            if (ReturnValue.Contains(6.ToString())) //Press
            {
                trMedia_Press.Visible = true;
                chkAll_Press.Checked = true;
            }

            if (ReturnValue.Contains(7.ToString())) //OUTDOOR
            {
                trMedia_OutDoor.Visible = true;
                chkAll_OutDoor.Checked = true;

                if (AppUser.GetCountry() == 58)
                { }
                else
                {
                    trMedia_OutDoor.Visible = false;
                }

            }

            if (ReturnValue.Contains(9.ToString())) //Internet
            {
                tr1.Visible = true;
                chkAll_Internet.Checked = true;
            }


        }

        private void SetCalendarDates()
        {


            DataTable dtTVCR = CommercialLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];
            DataTable dtPR = PressLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];
            DataTable dtOD = OutdoorLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];

            DataTable dtIN = InternetLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];

            List<DateTime> dates = new List<DateTime>();

            foreach (DataRow dr in dtTVCR.Rows)
            {
                dates.Add(Utility.ToDateTime(dr["RFDate"]));
            }
            foreach (DataRow dr in dtPR.Rows)
            {
                dates.Add(Utility.ToDateTime(dr["RFDate"]));
            }
            foreach (DataRow dr in dtOD.Rows)
            {
                dates.Add(Utility.ToDateTime(dr["RFDate"]));
            }

            foreach (DataRow dr in dtIN.Rows)
            {
                dates.Add(Utility.ToDateTime(dr["RFDate"]));
            }

            foreach (DateTime dt in dates)
            {

                RadCalendarDay d1 = new RadCalendarDay(calS);
                d1.Date = dt;
                d1.IsDisabled = false;
                d1.IsSelectable = true;

                d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d1.ItemStyle.ForeColor = System.Drawing.Color.White;

                calS.SpecialDays.Add(d1);

                RadCalendarDay d2 = new RadCalendarDay(calE);
                d2.Date = dt;
                d2.IsDisabled = false;
                d2.IsSelectable = true;

                d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d2.ItemStyle.ForeColor = System.Drawing.Color.White;


                calE.SpecialDays.Add(d2);
            }



        }


        protected void calS_ViewChanged(object sender, EventArgs e)
        {
            for (DateTime dt = calS.CalendarView.ViewStartDate; dt <= calS.CalendarView.ViewEndDate; dt.AddDays(1))
            {

            }
        }

        private static DataSet GetLookupDataSet()
        {
          //  if (HttpRuntime.Cache["dsLookUpByUser_ALL_" + AppUser.CurrUserID.ToString()] == null)
            //if (HttpContext.Current.Cache["dsLookUpByUser_ALL_" + AppUser.CurrUserID.ToString()] == null)
          //  {
                //Get Lookup Tables filtered by User / Company settings

                //DataSet ds = SPs.SpGetReportFilterLookupTables(AppUser.CurrUserID).GetDataSet();
                DataSet ds = SPs.GetLookupTables(AppUser.CurrUserID, "ALL").GetDataSet();
                ds.Tables[0].TableName = "MediaType";
                ds.Tables[1].TableName = "Media";
                ds.Tables[2].TableName = "Agency";
                ds.Tables[3].TableName = "Advertiser";
                ds.Tables[4].TableName = "Brand";
                ds.Tables[5].TableName = "Sector";
                ds.Tables[6].TableName = "SubSector";
                ds.Tables[7].TableName = "Category";
                ds.Tables[8].TableName = "Product";
                ds.Tables[9].TableName = "ProdVersion";
                //ds.Tables[10].TableName = "Program";

                //HttpContext.Current.Cache.Insert("dsLookUpByUser_ALL_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);

                HttpRuntime.Cache.Insert("dsLookUpByUser_ALL_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                return ds;

            //}
            //else
            //{
            //    //return ((DataSet)(HttpContext.Current.Cache["dsLookUpByUser_ALL_" + AppUser.CurrUserID.ToString()]));
            //    return ((DataSet)(HttpRuntime.Cache["dsLookUpByUser_ALL_" + AppUser.CurrUserID.ToString()]));
            //}
        }


        #region FillLists


        private void FillSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[5];
            DataView dv = dt.DefaultView;
            dt = dv.ToTable(true, "SectorName");
            
            lstSector.DataSource = dt;
            lstSector.DataBind();

            lstSector.Items.Insert(0, new ListItem("- ALL -", ""));
        }

        private void FillSubSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[6];

            string filter = "";
            filter += lstSector.SelectedValue != "" ? "SectorName='" + lstSector.SelectedValue + "'" : "";

            string sort = "SubSectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);



            dt = dv.ToTable(true, "SubSectorName");

            lstSubSector.DataSource = dt;
            lstSubSector.DataBind();

            lstSubSector2.DataSource = dt;
            lstSubSector2.DataBind();

            lstSubSector.Items.Insert(0, new ListItem("- ALL -", ""));
            lstSubSector2.Items.Insert(0, new ListItem("- ALL -", ""));
        }

        private void FillCategories()
        {
            DataTable dt = GetLookupDataSet().Tables[7];

            string filter = "1=1 ";
            filter += lstSector.SelectedValue != "" ? " AND SectorName='" + lstSector.SelectedValue + "'" : "";
            filter += lstSubSector.SelectedValue != "" ? " AND SubSectorName='" + lstSubSector.SelectedValue + "'" : "";

            string sort = "CategoryName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            dt = dv.ToTable(true, "CategoryName");

            lstCategory.DataSource = dt;
            lstCategory.DataBind();
            lstCategory.Items.Insert(0, new ListItem("- ALL -", ""));
        }

        private void FillAdvertisers()
        {
            DataTable dt = GetLookupDataSet().Tables[3];
            lstAdvertiser.DataSource = dt;
            lstAdvertiser.DataBind();

            lstAdvertiser.Items.Insert(0, new ListItem("- ALL -", ""));
        }

        private void FillAgencies()
        {
            DataTable dt = GetLookupDataSet().Tables[2];

            DataView dv = dt.DefaultView;
            dv.RowFilter = "AgencyName IS NOT NULL AND AgencyName <> ''";

            dt = dv.ToTable(true, "AgencyName");

            lstAgency.DataSource = dt;
            lstAgency.DataBind();
            lstAgency.Items.Insert(0, new ListItem("- ALL -", ""));
        }

        protected void lstSector_Changed(object sender, EventArgs e)
        {
            FillSubSectors();
            FillCategories();
           // pnlUpdate_ReportAllFilters.Update();
        }

        protected void lstSubSector_Changed(object sender, EventArgs e)
        {
            FillCategories();
           //pnlUpdate_ReportAllFilters.Update();
        }

        #endregion


        #region AutoComplete Functions

        [WebMethod]
        public static string[] AutoComplete_FillSectors(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[5];

            DataRow[] drs = dt.Select("SectorName LIKE '%" + prefixText + "%'");

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["SectorName"].ToString(), dr["SectorName"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }


        [WebMethod]
        public static string[] AutoComplete_FillSubSector(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[6];

            DataRow[] drs = dt.Select("SubSectorName LIKE '%" + prefixText + "%'");

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["SubSectorName"].ToString(), dr["SubSectorName"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }


        [WebMethod]
        public static string[] AutoComplete_FillCategories(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[7];

            DataRow[] drs = dt.Select("CategoryName LIKE '%" + prefixText + "%'");

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["CategoryName"].ToString(), dr["CategoryName"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }


        [WebMethod]
        public static string[] AutoComplete_FillAdvertiser(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[3];

            DataRow[] drs = dt.Select("AdvertiserName LIKE '%" + prefixText + "%'");

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["AdvertiserName"].ToString(), dr["AdvertiserName"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod(EnableSession = true)]
        public static string[] AutoComplete_FillBrand(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[4];


            DataRow[] drsUserWrite = dt.Select("BrandName = '" + prefixText + "'");

            if (drsUserWrite.Length == 1) //If user write and that item is in database
            {
                HttpContext.Current.Session["UserWriteProductName"] = prefixText;
                
            }
            else
            {
                HttpContext.Current.Session["UserWriteProductName"] = prefixText;
            }


            DataRow[] drs = dt.Select("BrandName LIKE '%" + prefixText + "%'");

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["BrandName"].ToString(), dr["BrandName"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillProduct(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "ProductName LIKE '%" + prefixText + "%'";

            //get brand 

            if (contextKey != null && contextKey != "" && contextKey != "0")
            {
                filter += " AND BrandCode = " + contextKey;
            }

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[8];

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProductName"].ToString(), dr["ProductName"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillVersion(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "ProdVersionName LIKE '%" + prefixText + "%'";

            //get brand 

            //if (contextKey != null && contextKey != "" && contextKey != "0")
            //{
            //}

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[9];

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProdVersionName"].ToString(), dr["ProdVersionName"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillAgency(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[2];

            DataRow[] drs = dt.Select("AgencyName LIKE '%" + prefixText + "%'");

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["AgencyName"].ToString(), dr["AgencyCode"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }




        #endregion


        #region Fill Media

        private void FillMediaTypes()
        {

            //lstMediaType.DataSource = GetLookupDataSet().Tables["MediaType"];
            //lstMediaType.DataBind(); 

            //lstMediaType.Items.Remove(lstMediaType.Items.FindByText("Press"));
            //lstMediaType.Items.Remove(lstMediaType.Items.FindByText("Outdoor"));

            ////lstMediaType.Items.Insert(0, new ListItem("All", "0"));

            //Utility.SelectListItemByText(lstMediaType, "TV");

            FillMedia();
        }

        private void FillMedia()
        {



            lstMedia_TV.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + Enums.MediaType.TV.GetHashCode(), "MediaName", DataViewRowState.OriginalRows);
            lstMedia_TV.DataBind();


            lstMedia_Radio.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + Enums.MediaType.RADIO.GetHashCode(), "MediaName", DataViewRowState.OriginalRows);
            lstMedia_Radio.DataBind();


            lstMedia_Cable.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + Enums.MediaType.CABLE.GetHashCode(), "MediaName", DataViewRowState.OriginalRows);
            lstMedia_Cable.DataBind();


            lstMedia_Press.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + Enums.MediaType.PRESS.GetHashCode(), "MediaName", DataViewRowState.OriginalRows);
            lstMedia_Press.DataBind();


            lstMedia_OutDoor.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + Enums.MediaType.OUTDOOR.GetHashCode(), "MediaName", DataViewRowState.OriginalRows);
            lstMedia_OutDoor.DataBind();

            lstMedia_Internet.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + Enums.MediaType.INTERNET.GetHashCode(), "MediaName", DataViewRowState.OriginalRows);
            lstMedia_Internet.DataBind();

        }

        #endregion


        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {

            //-----------------Alerts Start----------------------------------------------------------------------

            // Competition
            if (lstMediaType.SelectedItem.Value == 1.ToString() && lstCategory.SelectedItem.Text=="- ALL -") 
            {
                AjaxFuncs.MsgBox(this.Page,
                                "Please select the category.");
                return;
            }

            //Multimedia
            DownloadOnly = chkDownload.Checked;
            if (lstMediaType.SelectedItem.Value == 0.ToString() && DownloadOnly && (lstCategory.SelectedItem.Text == "- ALL -"))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your category, u must select the category.");
                return;
            }

            DownloadOnlyAdvertiser = chkDownloadAdvertiser.Checked;
            if (lstMediaType.SelectedItem.Value == 0.ToString() && DownloadOnlyAdvertiser && (lstAdvertiser.SelectedItem.Text == "- ALL -"))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your advertiser, u must select the advertiser.");
                return;
            }


            //-----------------Alerts End---------------------------------------------------------------------------------

            //------------------------Common Start------------------------------------------------
            bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
            bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);

            if (sDate < Utility.ToDateTime("01/01/2000"))
                sDate = Utility.ToDateTime("01/01/2000");

            if (eDate < Utility.ToDateTime("01/01/2000"))
                eDate = Utility.ToDateTime("01/01/2000");

            if ((sDate.ToString() != "01/01/2000 12:00:00 AM") && (eDate.ToString() != "01/01/2000 12:00:00 AM"))
            {


                mediaTypeCode = 0;

                foreach (ListItem itm in lstMedia_TV.Items)
                {
                    if (itm.Selected)
                        mediaCodes_TV += itm.Value + ",";
                }
                mediaCodes_TV = mediaCodes_TV.TrimEnd(',');


                foreach (ListItem itm in lstMedia_Radio.Items)
                {
                    if (itm.Selected)
                        mediaCodes_Radio += itm.Value + ",";
                }
                mediaCodes_Radio = mediaCodes_Radio.TrimEnd(',');


                foreach (ListItem itm in lstMedia_Cable.Items)
                {
                    if (itm.Selected)
                        mediaCodes_Cable += itm.Value + ",";
                }
                mediaCodes_Cable = mediaCodes_Cable.TrimEnd(',');


                foreach (ListItem itm in lstMedia_Press.Items)
                {
                    if (itm.Selected)
                        mediaCodes_Press += itm.Value + ",";
                }
                mediaCodes_Press = mediaCodes_Press.TrimEnd(',');


                foreach (ListItem itm in lstMedia_Internet.Items)
                {
                    if (itm.Selected)
                        mediaCodes_Internet += itm.Value + ",";
                }
                mediaCodes_Internet = mediaCodes_Internet.TrimEnd(',');


                foreach (ListItem itm in lstMedia_OutDoor.Items)
                {
                    if (itm.Selected)
                        mediaCodes_Outdoor += itm.Value + ",";
                }
                mediaCodes_Outdoor = mediaCodes_Outdoor.TrimEnd(',');


                Session["SearchMediaCodes_TV"] = mediaCodes_TV;
                Session["SearchMediaCodes_RD"] = mediaCodes_Radio;
                Session["SearchMediaCodes_CB"] = mediaCodes_Cable;
                Session["SearchMediaCodes_PR"] = mediaCodes_Press;
                Session["SearchMediaCodes_IN"] = mediaCodes_Internet;
                Session["SearchMediaCodes_OD"] = mediaCodes_Outdoor;


                sectorCode = lstSector.SelectedValue;
                subSectorCode = lstSubSector.SelectedValue;

                categoryCode = lstCategory.SelectedValue;
                //---------------------------Common End----------------------------------------------------------

                if (lstMediaType.SelectedItem.Value == 0.ToString()) // Multimedia
                {


                    advertiserCode = lstAdvertiser.SelectedValue;

                    if (acBrand.SelectedValue == "0") //not selected by user
                    {
                        if (!String.IsNullOrEmpty(Session["UserWriteProductName"].ToString()))
                        {

                            brandCode = Session["UserWriteProductName"].ToString();
                        }
                    }
                    else
                    {
                        brandCode = acBrand.SelectedValue == "0" ? "" : acBrand.SelectedValue;
                    }

                    DownloadOnlyProduct = chkDownloadProduct.Checked;
                    if (DownloadOnlyProduct && (brandCode == ""))
                    {
                        AjaxFuncs.MsgBox(this.Page,
                                         "To download all the videos, audios, or images related to your product, u must select the product.");
                        return;
                    }


                    productCode = acProduct.SelectedValue == "0" ? "" : acProduct.SelectedValue;
                    versionCode = acVersion.SelectedValue == "0" ? "" : acVersion.SelectedValue;
                    agencyCode = lstAgency.SelectedValue;

                    sTime = Utility.ToInt(lstStartTime.SelectedValue);
                    eTime = Utility.ToInt(lstEndTime.SelectedValue);


                    sPrice = tbPriceFrom.Text != "" ? Utility.ToInt(tbPriceFrom.Text) : 0;
                    ePrice = tbPriceTo.Text != "" ? Utility.ToInt(tbPriceTo.Text) : 0;

                    firstAppearanceOnly = chkFirstAppearance.Checked;
                    Response.Redirect(Server.UrlPathEncode(string.Format("report-all.aspx?sd={0}&ed={1}&mcTV={2}&mcRD={3}&mcCB={4}&mcPR={5}&mcOD={6}&s={7}&ss={8}&cc={9}&adv={10}&brnd={11}&prod={12}&ver={13}&agn={14}&st={15}&et={16}&sp={17}&ep={18}&fa={19}&mcIN={20}&down={21}&downpro={22}&downadv={23}", sDate.ToShortDateString().Replace("/", "_"), eDate.ToShortDateString().Replace("/", "_"), chkAll_TV.Checked, chkAll_Radio.Checked, chkAll_Cable.Checked, chkAll_Press.Checked, chkAll_OutDoor.Checked, sectorCode, subSectorCode, categoryCode, advertiserCode, brandCode, productCode, versionCode, agencyCode, sTime, eTime, sPrice, ePrice, firstAppearanceOnly, chkAll_Internet.Checked, DownloadOnly, DownloadOnlyProduct, DownloadOnlyAdvertiser)));

                }
                else //Competition
                {
                    if (chkCompetition.Checked == true) // if checked means ALL Brands
                    {
                        foreach (ListItem itm in chkLstCompetition.Items)
                        {
                            mediaCodes_Competition += itm.Value + ",";
                        }
                    }
                    else // user to select brands
                    {
                        foreach (ListItem itm in chkLstCompetition.Items)
                        {
                            if (itm.Selected)
                                mediaCodes_Competition += itm.Value + ",";
                        }
                    }

                    if (chkAdvertiser.Checked == true) // if checked means ALL Advertiser
                    {
                        foreach (ListItem itm in ChkAdvertiserList.Items)
                        {
                            mediaCodes_Competition += itm.Value + ",";
                        }
                    }
                    else // user to select brands
                    {
                        foreach (ListItem itm in ChkAdvertiserList.Items)
                        {
                            if (itm.Selected)
                                mediaCodes_Competition += itm.Value + ",";
                        }
                    }

                    mediaCodes_Competition = mediaCodes_Competition.TrimEnd(',');
                    Session["SearchMediaCodes_Competition"] = mediaCodes_Competition;

                    // pnlUpdate_ReportAllFilters.Update();
                    Response.Redirect(Server.UrlPathEncode(string.Format("report-competition.aspx?sd={0}&ed={1}&mcTV={2}&mcRD={3}&mcCB={4}&mcPR={5}&mcOD={6}&s={7}&ss={8}&cc={9}&mcIN={10}&cComp={11}",
                    sDate.ToShortDateString().Replace("/", "_"), eDate.ToShortDateString().Replace("/", "_"), chkAll_TV.Checked, chkAll_Radio.Checked, chkAll_Cable.Checked, chkAll_Press.Checked, chkAll_OutDoor.Checked, sectorCode, subSectorCode, categoryCode, chkAll_Internet.Checked, chkCompetition.Checked)));
                }
            }
            else
            {
                string script = "alert(\"Please select date first!\");";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
            }
        }

        protected void lstMediaType_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (lstMediaType.SelectedItem.Value==0.ToString()) //Multimedia
            {
                pnlforMultimedia.Visible = true;
            }
            else //Competition
            {
                pnlforMultimedia.Visible = false;
            }
           //pnlUpdate_ReportAllFilters.Update();
        }

        protected void lstCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
           
            
            if (lstMediaType.SelectedItem.Value != 0.ToString()) //Competition
            {
                if (!String.IsNullOrEmpty(lstCategory.SelectedItem.Value))
                {
                    BindBrandsAccordingtoCategories(lstCategory.SelectedItem.Value);
                }

                if (lstCategory.SelectedItem.Value == "") // if user select ALL
                {
                    chkLstCompetition.Items.Clear();
                    chkLstCompetition.DataSource = null;
                    chkLstCompetition.DataBind();
                }
               

                PnlCompetitionBrands.Visible = true;
            }
            else
            {
                PnlCompetitionBrands.Visible = false;
            }
         
        }

        private void BindBrandsAccordingtoCategories(String SelectedCategory)
        {
            DataTable dt = RfController.GetCompetitionBrands_CategoryName(SelectedCategory);
            if (dt.Rows.Count > 0)
            {
                chkLstCompetition.DataSource = dt;
                chkLstCompetition.DataBind();
            }
            DataTable dtAdvretisers = RfController.GetCompetitionAdvertisers_CategoryName(SelectedCategory);
            if (dtAdvretisers.Rows.Count > 0)
            {
                ChkAdvertiserList.DataSource = dtAdvretisers;
                ChkAdvertiserList.DataBind();
            }
         }

        protected void chkCompetition_CheckedChanged(object sender, EventArgs e)
        {
            divAdvertisersList.Visible = false;
            for (int i = 0; i < ChkAdvertiserList.Items.Count; i++)
            {
                ChkAdvertiserList.Items[i].Selected = false;
            }

            if (chkAdvertiser.Checked) {
                lblErrorMsg.Visible = true;
                lblErrorMsg.Text = "Only one choice can be made at a time.";
                chkAdvertiser.Checked = false;
              
            }
            else
            {

                if (chkCompetition.Checked)
                    divCompetition.Visible = false;
                else
                    divCompetition.Visible = true;
            }
        }

        protected void chkAdvertiser_CheckedChanged(object sender, EventArgs e)
        {
            divCompetition.Visible = false;
            divCompetition.Visible = false;
            for (int i = 0; i < chkLstCompetition.Items.Count; i++)
            {
                chkLstCompetition.Items[i].Selected = false;
            }
            if (chkCompetition.Checked)
            {
                lblErrorMsg.Visible = true;
                lblErrorMsg.Text = "Only one choice can be made at a time.";
                chkCompetition.Checked = false;
               
            }
            else
            {
                lblErrorMsg.Visible = false;
                if (chkAdvertiser.Checked)
                    divAdvertisersList.Visible = false;
                else
                    divAdvertisersList.Visible = true;
            }
        }
    }
}